<?php
// CURL or fopen of URLs
class URLConnection {

	/**
	 * The url
	 */
	protected $url;
	
	/**
	 * The cache contents of the url
	 */		
	protected $contents;
	
	/**
	 * Default constructor
	 */
	public function __construct($url) {
		$this->url = $url;
	}

	/**
	* 'Getters' to return contents and url
	*/
	public function getContents(){
		$this->readAndCacheContents();
		return $this->contents;
	}
	public function getUrl(){
		return $this->url;
	}
	
	/**
	* Reads and cache the contents of the url
	*/
	public function readAndCacheContents() {
		if ( !empty($this->contents) ) {
			return;
		}
		
		if ( function_exists('curl_init') ) {
			$ch = curl_init();		
			curl_setopt($ch, CURLOPT_URL, $this->url);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Charset: UTF-8;'));		// lets hope for a UTF-8 version
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Cinnamon Statistics Engine/'. Cinnamon::getVersion());
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
			$this->contents = curl_exec($ch);
			curl_close($ch);
		} else {
			$fh = fopen($this->url, 'rb');
			if ( $fh ) {
				$this->contents = stream_get_contents($fh);
				fclose($fh);		
			}
		}
	
	}
}
?>